#pragma once

#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "TheadPool.hpp"
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <functional>

using namespace LogModule;
using namespace ThreadPoolModule;

const static int default_sockfd = -1;
const static int backlog = 5;

using func_t = std::function<std::string(const std::string&, InetAddr&)>;

class TcpServer : public NoCopy
{
public:
    TcpServer(uint16_t port, func_t func)
        :_port(port)
        ,_listen_sockfd(default_sockfd)
        ,_isrunning(false)
        ,_func(func)
    {}

    void Init()
    {
        //创建套接字
        _listen_sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listen_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(SOCKET_ERR);
        }

        LOG(LogLevel::INFO) << "socket success: " << _listen_sockfd;

        //绑定端口号
        InetAddr local(_port);
        int n = bind(_listen_sockfd, local.NetAddrPtr(), local.NetAddrLen());
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success: " << _listen_sockfd;

        //设置监听状态
        n = listen(_listen_sockfd, backlog);
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success: " << _listen_sockfd;
    }

    class ThreadData
    {
    public:
        ThreadData(int sockfd, InetAddr& addr, TcpServer* tsvr)
            :_sockfd(sockfd)
            ,_addr(addr)
            ,_tsvr(tsvr)
        {}
        int _sockfd;
        InetAddr _addr;
        TcpServer* _tsvr;
    };

    void Service(int sockfd, InetAddr& peer)
    {
        char buffer[1024];
        while(1)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if(n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::DEBUG) << peer.StringAddr() << " say: " << buffer;
                
                std::string res = _func(buffer, peer);
                // std::string result = buffer;
                // result = "### " + result;

                write(sockfd, res.c_str(), res.size());
            }
            else if(n == 0)
            {
                LOG(LogLevel::DEBUG) << peer.StringAddr() << " exit...";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::DEBUG) << peer.StringAddr() << " error...";
                close(sockfd);
                break;
            }
        }
    }

    static void* Routine(void* args)
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_tsvr->Service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(sockaddr_in);
            int sockfd = accept(_listen_sockfd, CONV(peer), &len);
            if(sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "accept success, peer addr: " << addr.StringAddr();


            //线程版本
            ThreadData* td = new ThreadData(sockfd, addr, this);
            pthread_t tid;
            pthread_create(&tid, nullptr, Routine, td);
            
            // //多进程版本
            // pid_t id = fork();
            // if(id < 0)
            // {
            //     LOG(LogLevel::FATAL) << "fork error";
            //     exit(FORK_ERR);
            // }
            // else if(id == 0)    //子进程
            // {
            //     close(_listen_sockfd);
            //     if(fork() > 0) exit(OK);

            //     Service(sockfd, addr);
            //     exit(OK);
            // }   
            // else                //父进程
            // {
            //     close(sockfd);
            //     pid_t rid = waitpid(id, nullptr, 0);
            // }

        }
        _isrunning = false;
    }

    ~TcpServer(){}
private:
    uint16_t _port;
    int _listen_sockfd;
    bool _isrunning;

    func_t _func;
};
